<?php
namespace Api\Controller;
use Think\Controller;
class LoginController extends PublicController {

	//***************************
	//  前台登录接口
	//***************************
    public function dologin(){
		session_destroy();
		$name = trim($_POST['username']);	//接受“会员账号”
		$pwd  = md5(md5($_POST['pwd']));	//接受“会员密码”
		if (!$name || !$pwd) {
			echo json_encode(array('status'=>0,'err'=>'请输入账号或密码！'));
			exit();
		}

		$user = M('user');
		$where['name'] = $name;
		$where['pwd'] = $pwd;
		$usrNum = $user->where($where)->find();
		///echo $user->_sql();exit;
		if($usrNum){
			@session_start();
			$_COOKIE['sessionid'] = session_id();
			//$_SESSION['sessionid']=session_id();
			$_SESSION['LoginCheck']=md5($name);
			$_SESSION['LoginName']=$name;
			$_SESSION['ID']=$usrNum['id'];
			$_SESSION['photo']=$usrNum['photo'];
			
			echo json_encode(array('status'=>1,'session'=>$_SESSION));
			exit();
		}else{
			echo json_encode(array('status'=>0,'err'=>'账号密码错误！'));
			exit();
		}		 
	}

	//***************************
	//  授权登录接口
	//***************************
	public function authlogin(){
		$openid = $_POST['openid'];
		if (!$openid) {
			echo json_encode(array('status'=>0,'err'=>'授权失败！'.__LINE__));
			exit();
		}
		$con = array();
		$con['openid']=trim($openid);
		$uid = M('user')->where($con)->getField('id');
		if ($uid) {
			$userinfo = M('user')->where('id='.intval($uid))->find();
			if (intval($userinfo['del'])==1) {
				echo json_encode(array('status'=>0,'err'=>'账号状态异常！'));
				exit();
			}
			$err = array();
			$err['ID'] = intval($uid);
			$err['NickName'] = $_POST['NickName'];
			$err['HeadUrl'] = $_POST['HeadUrl'];
			echo json_encode(array('status'=>1,'arr'=>$err));
			exit();
		}else{
			$data = array();
			$data['name'] = $_POST['NickName'];
			$data['uname'] = $_POST['NickName'];
			$data['photo'] = $_POST['HeadUrl'];
			$data['sex'] = $_POST['gender'];
			$data['openid'] = $openid;
			$data['source'] = 'wx';
			$data['addtime'] = time();
			if (!$data['openid']) {
				echo json_encode(array('status'=>0,'err'=>'授权失败！'.__LINE__));
				exit();
			}
			$res = M('user')->add($data);
			if ($res) {
				$err = array();
				$err['ID'] = intval($res);
				$err['NickName'] = $data['name'];
				$err['HeadUrl'] = $data['photo'];
				echo json_encode(array('status'=>1,'arr'=>$err));
				exit();
			}else{
				echo json_encode(array('status'=>0,'err'=>'授权失败！'.__LINE__));
				exit();
			}
		}
	}


	//***************************
	//  前台注册接口
	//***************************
  	public function register(){
	  	$name = trim($_POST['user']);
	  	$pwd  = md5(md5($_POST['pwd']));
	    $pwds = md5(md5($_POST['pwds']));
	   if($pwd!=$pwds) {
			echo json_encode(array('status'=>0,'err'=>'两次输入密码不同！'));
			exit();
		}

		$user=M('user');
		$where = array();
		$where['name']=$name;
		$count=$user->where($where)->count();
		if($count) {
			echo json_encode(array('status'=>0,'err'=>'用户名已被注册了！'));
			exit();
		}

		$check_mob=$user->where('tel='.trim($_POST['tel']))->count();
		if($check_mob) {
			echo json_encode(array('status'=>0,'err'=>'手机号已存在！'));
			exit();
		}
		$data = array();
		$data['name'] = $name;
        $data['qx'] = 6;

		$data['pwd']   = $pwd;
		$data['tel']   = trim($_POST['tel']);
		$data['addtime'] = time();
		$res = $user->add($data);
		if ($res) {
			$_SESSION['LoginName']=$name;
			$_SESSION['ID']=$res;
			$arr =array();
			$arr['status']=1;
			$arr['uid'] = $res;
			$arr['LoginName'] = $name;
			echo json_encode($arr);
			exit();
		}else{
			echo json_encode(array('status'=>0,'err'=>'注册失败！'));
			exit();
		}
	}

    /**
     * 微信授权登录
     * @author tiedong
     * $data 2017-01-10
     */
	public function wxLogin(){
		$wx_config = C('weixin');
    	$appid = $wx_config['appid'];
    	$secret = $wx_config['secret'];
        $code = trim($_GET['code']);
		if (!$code) {
			echo json_encode(array('status'=>0,'err'=>'非法操作！'));
			exit();
		}
		if (!$appid || !$secret) {
			echo json_encode(array('status'=>0,'err'=>'非法操作！'.__LINE__));
			exit();
		}
		$get_token_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
        $res = $this->_get_url_contents($get_token_url);
        $userInfo=json_decode($res,true);
        if (empty($userInfo['openid'])) {
            $this->json_error("ffff请重新授权！");
        }
        $sessionKey = $userInfo['session_key'];
        $userId = M("user")->where("openid='".$userInfo['openid']."'")->find();
        if (!empty($userId)) {
            $ret = array(
                't_session' => $sessionKey,
                'userId' => $userId['id'],
                'msg' => "登录成功"
            );
            $this->setUserInfo($userId,$sessionKey);
        } else {
            $data = array(
                'openid'=> $userInfo['openid'],
                'addtime' =>time()
            );
            $userId = M("user")->add($data);
            $_SESSION['userId']=$userId;
            $ret = array(
                't_session' => $sessionKey,
                'userId' => $userId,
                'msg' => "登录成功"
            );
            $this->getUserDetail($userId,$sessionKey);
        }
        $this->json_result($ret);
		exit();
	}

    /**
     * 解密小程序返回encryptedData
     * @author tiedong
     * @date 2018-01-09
     */
    public function getUserInfo()
    {
        include_once __LOGIN_ROOT__.'/extend/Login/wxBizDataCrypt.php';
        $wx_config = C('weixin');
        $appid = $wx_config['appid'];
        $sessionKey = $_POST['t_session'];
        $encryptedData = $_POST['encryptedData'] ? $_POST['encryptedData'] : '';
        $iv = $_POST['iv'] ? $_POST['iv'] : '';
        if ( empty($sessionKey) || empty($iv) ) {
            $this->json_error("参数有误！");
        }
        $pc = new \WXBizDataCrypt($appid,$sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
        if( !empty($data) ){
            $userInfo = json_decode($data,true);
            if( is_array($userInfo) && count($userInfo) ){
                if( !empty($userInfo['openId']) ){
                    $openId = $userInfo['openId'];
                    $user = M("user")->where("openid='$openId'")->find();
                    if (!empty($user['name'])) {
                        $this->setUserInfo($user,$sessionKey);
                    } else {
                        $updateData = array(
                            'name' => $userInfo['nickName'],
                            'photo' => $userInfo['avatarUrl'],
                            'sex' => $userInfo['gender'],
                        );
                        M("user")->where("openid='$openId'")->save($updateData);
                    }

                }
            }
        }
        $this->json_result('请求成功');

    }
    /**
     * 读取URL的内容
     *
     * @author wechan
     * @param string $url
     * @param array $data
     */
    private function _get_url_contents($url, $data=array())
    {
        $ch=curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        !empty($data) && curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
        curl_exec($ch);
        $result=ob_get_contents();
        ob_clean();
        curl_close($ch);
        return $result;
    }

    /**
     * 获取用户的基本信息保存到redis
     * @author tiedong
     */
    public function getUserDetail( $uId,$sessionKey)
    {
        $data = M("user")->where("id=".$uId)->find();
        $this->setUserInfo($data,$sessionKey);
    }

	//***************************
	//  前台退出登录接口
	//***************************
	public function logout(){
		unset($_SESSION['uid']);  
		unset($_SESSION['LoginName']);
		session_destroy();
		echo json_encode(array('status'=>1));
		exit();
	}
	
}